package com.block.datapush.service.apipush;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.block.common.enums.ProfitSharingEnum;
import com.block.common.model.dto.ThirdInfoDTO;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.IApplicationInfoService;
import com.block.common.service.LogFactory;
import com.block.common.service.merchant.IMerchantThirdBaseInfoService;
import com.block.common.util.RSAUtil;
import com.block.common.util.RSAUtils;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.apipush.utils.XiaoMeiYiRongUtil;
import com.block.datapush.service.apipush.utils.XinYongPaiUtil;
import com.block.datapush.service.apipush.utils.YunQiUtil;
import com.block.db.entity.ApplicationInfo;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.entity.MerchantBaseInfo;
import com.block.db.mapper.MerchantThirdBaseInfoMapper;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.math.BigDecimal;
import java.security.*;
import java.security.spec.X509EncodedKeySpec;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 小美易融
 */
@Service
public class XiaoMeiYiRongPushApiService implements IPushApiService {

    private static final Logger log = LogFactory.getPushLog();

    @Autowired
    IMerchantThirdBaseInfoService merchantThirdBaseInfoService;
    @Autowired
    IApplicationInfoService applicationInfoService;


    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        String queryUrl = pushApiKeyParam.getCheckUrl();


        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("customerName", memberSourceInfo.getRealname());
        bizMap.put("phoneMd5", memberSourceInfo.getMobileMd5());
        bizMap.put("sex", memberSourceInfo.getSex() == 1 ? 0 : 1);
        bizMap.put("age", memberSourceInfo.getAge());
        bizMap.put("ip", memberSourceInfo.getReqIp());
        bizMap.put("loanAmount", XiaoMeiYiRongUtil.getloan(memberSourceInfo.getLoanAmount()));
        bizMap.put("mapCode", memberSourceInfo.getCityCode());
        bizMap.put("extName", memberSourceInfo.getCity());
        bizMap.put("creditCardLimit", XiaoMeiYiRongUtil.getyuqi(memberSourceInfo.getYuqi()));
        bizMap.put("accumulationFund", XiaoMeiYiRongUtil.getGjj(memberSourceInfo.getGjj()));
        bizMap.put("socialSecurity", XiaoMeiYiRongUtil.getshebao(memberSourceInfo.getShebao()));
        bizMap.put("sesameSeeds", XiaoMeiYiRongUtil.getZhimaScore(memberSourceInfo.getZhima()));
        bizMap.put("existRoom", XiaoMeiYiRongUtil.getHouse(memberSourceInfo.getHouse()));
        bizMap.put("vehicleCondition", XiaoMeiYiRongUtil.getCar(memberSourceInfo.getCar()));
        bizMap.put("commercialInsurance", XiaoMeiYiRongUtil.getbaodan(memberSourceInfo.getBaoxian()));
        bizMap.put("occupation", XiaoMeiYiRongUtil.getGongZuo(memberSourceInfo.getGongzuo()));
        bizMap.put("monthlyIncome", XiaoMeiYiRongUtil.getShouRu(memberSourceInfo.getShouru()));
        bizMap.put("lengthOfMaturity", XiaoMeiYiRongUtil.getloanTime(memberSourceInfo.getLoanTime()));
        bizMap.put("monthlyOperatingFlow", "-2");
        bizMap.put("monthlyInvoicingRevenue", "-2");
        bizMap.put("individualLicense", "-2");
        bizMap.put("entrepreneurLicense", "-2");


        String requestId = UUID.randomUUID().toString();

        extJson.put("requestId", requestId);

        bizMap.put("requestId", requestId);
        bizMap.put("identify", pushApiKeyParam.getApiKey());


        String data = SecureUtil.aes(pushApiKeyParam.getApiSecret().getBytes()).encryptBase64(JSON.toJSONString(bizMap));

        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("data", data);
        paramMap.put("companyId", pushApiKeyParam.getApiCode());


        log.info("【小美易融双授权】撞库开始【queryUrl】{}【bizMap】{}【paramMap】{}", queryUrl, JSON.toJSONString(bizMap), JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(queryUrl)
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        JSONObject resultObject = JSON.parseObject(result);

        log.info("【小美易融双授权】撞库结束【resultDes】{}", resultObject.toJSONString());

        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");

        pushApiResult.setCode(code + "");
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(bizMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "200")) {
            JSONObject data1 = resultObject.getJSONObject("data");
            Integer status = data1.getInteger("status");
            if (StrUtil.equals(String.valueOf(status), "1")) {
                pushApiResult.setCode(code + "|"+status);
                String logo = data1.getString("logo");
                String productName = data1.getString("productName");
                String companyName = data1.getString("companyName");
                ThirdInfoDTO thirdInfoDTO = new ThirdInfoDTO();
                thirdInfoDTO.setInfoId(Integer.valueOf(pushApiKeyParam.getInfoId()));
                thirdInfoDTO.setInfoName(pushApiKeyParam.getInfoName());
                thirdInfoDTO.setOrderNo(orderNo);
                JSONObject infoObject = new JSONObject();
                infoObject.put("orderNo", requestId);
                infoObject.put("productId", requestId);
                infoObject.put("productName", productName);
                infoObject.put("companyName", companyName);
                infoObject.put("companyLogo", logo);
                infoObject.put("maxLoanAmount", "200000");
                infoObject.put("maxLoanRate", "8");
                infoObject.put("minLoanRate", "1");
                infoObject.put("businessInfo", pushApiKeyParam.getInfoName());
                JSONArray jsonArray = new JSONArray();
                infoObject.put("protocalList", jsonArray);
                thirdInfoDTO.setInfoObject(infoObject);


                //进行分润操作
                String priceType = pushApiKeyParam.getPriceType();
                BigDecimal typeRate = pushApiKeyParam.getTypeRate();
                if (ProfitSharingEnum.PROFITPRICE.getValue().equals(priceType)){
                    BigDecimal price = data1.getBigDecimal("price");
                    if (price == null || price.compareTo(new BigDecimal(0.00)) == -1){
                        pushApiResult.setPushSuccess(false);
                        return pushApiResult;
                    }
                    BigDecimal priceRight = typeRate.multiply(price);
                    pushApiResult.setPrice(price);
                    pushApiResult.setPriceRight(priceRight);
                }

                boolean save = merchantThirdBaseInfoService.saveThirdInfo(thirdInfoDTO);
                if (save) {
                    pushApiResult.setPushSuccess(true);
                    pushApiResult.setOutOrderNo(requestId);
                } else {
                    pushApiResult.setMessage("保存撞库数据失败");
                }
            }
        }
        return pushApiResult;
    }

    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        return null;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        pushApiResult.setOrderNo(orderNo);


        String requestUrl = pushApiKeyParam.getRegisterUrl();

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("customerName", memberSourceInfo.getRealname());
        bizMap.put("phone", memberSourceInfo.getMobile());
        bizMap.put("sex", memberSourceInfo.getSex() == 1 ? 0 : 1);
        bizMap.put("age", memberSourceInfo.getAge());
        bizMap.put("ip", memberSourceInfo.getReqIp());
        bizMap.put("loanAmount", XiaoMeiYiRongUtil.getloan(memberSourceInfo.getLoanAmount()));
        bizMap.put("mapCode", memberSourceInfo.getCityCode());
        bizMap.put("extName", memberSourceInfo.getCity());
        bizMap.put("creditCardLimit", XiaoMeiYiRongUtil.getyuqi(memberSourceInfo.getYuqi()));
        bizMap.put("accumulationFund", XiaoMeiYiRongUtil.getGjj(memberSourceInfo.getGjj()));
        bizMap.put("socialSecurity", XiaoMeiYiRongUtil.getshebao(memberSourceInfo.getShebao()));
        bizMap.put("sesameSeeds", XiaoMeiYiRongUtil.getZhimaScore(memberSourceInfo.getZhima()));
        bizMap.put("existRoom", XiaoMeiYiRongUtil.getHouse(memberSourceInfo.getHouse()));
        bizMap.put("vehicleCondition", XiaoMeiYiRongUtil.getCar(memberSourceInfo.getCar()));
        bizMap.put("commercialInsurance", XiaoMeiYiRongUtil.getbaodan(memberSourceInfo.getBaoxian()));
        bizMap.put("occupation", XiaoMeiYiRongUtil.getGongZuo(memberSourceInfo.getGongzuo()));
        bizMap.put("monthlyIncome", XiaoMeiYiRongUtil.getShouRu(memberSourceInfo.getShouru()));
        bizMap.put("lengthOfMaturity", XiaoMeiYiRongUtil.getloanTime(memberSourceInfo.getLoanTime()));
        bizMap.put("monthlyOperatingFlow", "-2");
        bizMap.put("monthlyInvoicingRevenue", "-2");
        bizMap.put("individualLicense", "-2");
        bizMap.put("entrepreneurLicense", "-2");
        String requestId = extJson.getString("requestId");

        bizMap.put("requestId", requestId);
        bizMap.put("identify", pushApiKeyParam.getApiKey());



        String data = SecureUtil.aes(pushApiKeyParam.getApiSecret().getBytes()).encryptBase64(JSON.toJSONString(bizMap));

        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("data", data);
        paramMap.put("companyId", pushApiKeyParam.getApiCode());

        log.info("【小美易融双授权】导单开始【queryUrl】{}【bizMap】{}【paramMap】{}", requestUrl, JSON.toJSONString(bizMap), JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(requestUrl)
                .body(JSON.toJSONString(paramMap))
                .execute().body();

        JSONObject resultObject = JSON.parseObject(result);


        log.info("【小美易融双授权】导单结束【result】{}", resultObject.toJSONString());


        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");

        pushApiResult.setCode(code + "");
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(bizMap));
        pushApiResult.setResultInfo(result);

        ThirdInfoDTO thirdInfoDTO = new ThirdInfoDTO();
        thirdInfoDTO.setOrderNo(orderNo);
        thirdInfoDTO.setRetCode(String.valueOf(code));
        thirdInfoDTO.setRetMsg(msg);
        thirdInfoDTO.setResultInfo(result);
        thirdInfoDTO.setStatus("FAILED");

        if (StrUtil.equals(String.valueOf(code), "200")) {
            JSONObject data1 = resultObject.getJSONObject("data");
            Integer status = data1.getInteger("status");
            if (StrUtil.equals(String.valueOf(status), "1")) {
                String message = resultObject.getString("message");
                pushApiResult.setCode(code + "|"+status);
                pushApiResult.setMessage(message);
                thirdInfoDTO.setStatus("SUCCESS");
            }
        }
        merchantThirdBaseInfoService.updateThirdInfo(thirdInfoDTO);
        if (StrUtil.equals(String.valueOf(code), "200")) {
            JSONObject data1 = resultObject.getJSONObject("data");
            Integer status = data1.getInteger("status");
            if (StrUtil.equals(String.valueOf(status), "1")) {
                pushApiResult.setPushSuccess(true);
                pushApiResult.setSettleFlag(true);
                pushApiResult.setStatus(PushStatusEnum.SUCCESS.getValue());
                return pushApiResult;
            }
        }
        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        return pushApiResult;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        return pushApiResult;
    }

    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();
        return noticeParamDTO;
    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();
        return jsonObject;
    }

    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        ProtocolParamResult paramResult = new ProtocolParamResult();
        return paramResult;
    }
}
